package encoding.convert;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 操作文本文档时，尽量使用字符流。字节流容易产生乱码问题。<br>
 * 字符转换<br>
 * 此处使用的是字符流
 */
public class EncodingConvert {
	public static void main(String[] args) throws Exception {
		String filePath = "D:\\abc.java";
		
		CpdetectorEncoding ce = new CpdetectorEncoding();
		String charset = ce.getEncoding(filePath, false).name();
		System.out.println(charset);
		
		InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), charset);
		StringBuffer sb = new StringBuffer();
		char[] cbuf = new char[1024];
		int read;
		while ((read = isr.read(cbuf)) != -1) {
			sb.append(cbuf, 0, read);
		}
		isr.close();
		
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
		osw.write(sb.toString());
		osw.flush();
		osw.close();
		
	}

}
